package main

import (
	"os"
	"fmt"
	"strings"

	"qiniu-upload/etc"
	"qiniu-upload/upload"
)

func main() {
	/*fmt.Println(
		"json:", etc.Param.Json,
		"dir:", etc.Param.Dir,
		"file:", etc.Param.File,
		"path:", etc.Param.Path,
		"cove:", etc.Param.Cove,
		"zip:", etc.Param.Zip,
		"rem:", etc.Param.Rem,
	)*/

	// 获取上传对象
	up := upload.NewUpload(etc.Domain, etc.Bucket, etc.AccessKey, etc.SecretKey)

	// 覆盖上传
	up.SetCover(etc.Param.Cove)

	// 设置上传根目录
	up.SetRootDir(etc.Param.Dir)

	if len(etc.Param.File) > 0 {
		if len(etc.Param.Zip) > 0 {
			if err := etc.ZipCompress(etc.Param.File, etc.Param.Zip, etc.ZipPassword); err != nil {
				fmt.Println("zip compress error:", err)
				exit(1)
			}
			// 上传压缩文件
			uploadFile(up, etc.Param.Zip)

			// 删除压缩文件
			if etc.Param.Rem {
				os.Remove(etc.Param.Zip)
			}
		} else {
			// 上传单个文件
			uploadFile(up, etc.Param.File)
		}
	} else {
		if len(etc.Param.Zip) > 0 {
			if err := etc.ZipCompress(etc.Param.Dir, etc.Param.Zip, etc.ZipPassword); err != nil {
				fmt.Println("zip compress error:", err)
				exit(1)
			}

			// 上传压缩文件
			uploadFile(up, etc.Param.Zip)

			// 删除压缩文件
			if etc.Param.Rem {
				os.Remove(etc.Param.Zip)
			}
		} else {
			uploadDir(up, etc.Param.Dir)
		}
	}

	fmt.Println("upload success.")

	exit(0)
}

// 退出程序
func exit(code int)  {
	if etc.OS() == "windows" {
		var input string
		fmt.Scanln(&input)
	}

	os.Exit(code)
}

// 上传文件
func uploadFile(up *upload.Upload, fileName string) {
	ret, err := up.UploadFile(fileName, etc.Param.Path)
	if err != nil {
		fmt.Println("upload error:", err)
		return
	}

	output(ret)

	// 刷新文件CDN
	if etc.Param.Cove {
		err := up.RefreshUrls([]string{ret.Url})
		if err != nil {
			fmt.Println("refresh file error:", err)
		} else {
			fmt.Println("refresh file success:", ret.Url)
		}
	}
}

// 上传目录
func uploadDir(up *upload.Upload, dir string) {
	files, err := etc.GetFiles(dir)
	if len(files) <= 0 || err != nil {
		fmt.Println("error: no such file or directory")
		exit(1)
	}

	up.SetBase(true)

	// 上传文件
	for _, file := range files {
		ret, err := up.UploadFile(file, etc.Param.Path)
		if err != nil {
			fmt.Println("upload error:", err)
			continue
		}

		output(ret)
	}

	// 刷新目录CDN
	if etc.Param.Cove {
		refresh := strings.TrimRight(etc.Domain, "/") + "/" + etc.Param.Path
		err := up.RefreshDirs([]string{refresh})
		if err != nil {
			fmt.Println("refresh dir error:", err)
		} else {
			fmt.Println("refresh dir success:", refresh)
		}
	}
}

func output(ret *upload.Result) {
	if ret != nil {
		fmt.Println("file:", ret.Url, "md5:", ret.Md5, "size:", ret.Fsize)
	}
}
